<script lang="ts" setup>
import { h, ref, reactive, watch, computed } from 'vue'
import { aesEncrypt, createRef, refs } from 'dsrz/utils'
import {studentStatus } from "@/enum/index";
import selectClassEl from './selectClassEl.vue'

// 定义 emits
const emit = defineEmits<{
  confirm: [data: any]
}>()

const visible = ref<boolean>(false)
const title = ref<string>('')

const isImportMode = computed(() => {
  return title.value == '学生数据导入'
})

const formDetails = ref([])
// 创建响应式的表单详情
const formDetailsData = reactive({} as any)

const getParams = (value: any) => {
    formDetails.value = value.data || []
    title.value = value.title || ''
    open()
}

const form = reactive({
  size: 'default',
  details: formDetailsData,
  items: [
    {
      label: '所属年级',
      prop: 'grantId',
      is: 'currency-select',
      display: () => isImportMode.value,
      bind: {
        options: formDetails,
        clearable: true,
        filterable: true,
        placeholder: '请选择年级',
        props: {
            label: 'name',
            value: 'id',
        }
      },
    },
    {
      label: '选择文件',
      prop: 'selectFile',
      is: 'currency-upload',
      display: () => isImportMode.value,
      bind: {
        limit: 1,
        accept: '.xlsx,.xls',
        buttonTitle: '选择文件',
      },
    },
    {
      label: '年级',
      prop: 'id',
      is: 'currency-select',
      display: () => !isImportMode.value,
      bind: {
        options: formDetails,
        clearable: true,
        filterable: true,
        placeholder: '请选择年级',
        props: {
            label: 'name',
            value: 'id',
        }
      },
      on: {
        change: (e: any) => {
            formDetailsData.id = e
        }
      }
    },
     {
       label: '班级',
       is: h(selectClassEl),
       display: () => !isImportMode.value,
       bind: {
         formDetailsData: formDetailsData
       },
       on: {
         change: (selectedClasses: any[]) => {
           console.log('== 选中的班级数据:', selectedClasses)
           // 将选中的班级数据存储到表单详情中
           formDetailsData.selectedClasses = selectedClasses
           // 或者只存储班级ID
           formDetailsData.classIds = selectedClasses.map(item => item.id)
         }
       }
     },
    {
      label: '学籍状态',
      prop: 'status',
      is: 'currency-select',
      display: () => !isImportMode.value,
      bind: {
        options: studentStatus,
        clearable: true,
        filterable: true,
        placeholder: '请选择学籍',
      },
    },
  ],
  rules: {
    grantId: [{ required: true, message: '请选择年级', trigger: 'blur' }],
    id: [{ required: true, message: '请选择年级', trigger: 'blur' }],
    status: [{ required: true, message: '请选择学籍', trigger: 'blur' }],
  },
})

const handleConfirm = async () => {
  // 通过全局 refs 访问表单实例
  const formInstance = refs.formRef
  console.log('获取 班级职位 form 表单 ', form.details)
  
  if (formInstance) {
    try {
      // 触发表单验证
      await formInstance.validate()
      // 验证通过，执行确认逻辑
      emit('confirm', form.details)
      cancel()
    } catch (error) {
      return false
    }
  } else {
    return false
  }
}

// 重置表单逻辑
const resetForm = () => {
    // 清空表单数据
    Object.keys(form.details).forEach(key => {
        delete form.details[key]
    })
    
    // 如果使用了 Element Plus 的表单，也重置表单验证状态
    const formInstance = refs.formRef
    if (formInstance) {
        formInstance.resetFields()
    }
}

const cancel = () => {
    resetForm()
    visible.value = false
}

const open = () => {
    visible.value = true
}



defineExpose({
  getParams,
})
</script>

<template>
    <CurrencyDialog
      v-model="visible"
      :title="title"
      :size="form.size"
      @cancel="cancel"
      @confirm="handleConfirm"
      >
      <div v-if="!isImportMode" class="title">范围选择:</div>
      <CurrencyForm
        ref="formRef"
        v-model="form.details"
        :items="form.items"
        :rules="form.rules"
      />
    </CurrencyDialog>
</template>

<style scoped lang="scss">
.title {
    margin-left: 20px;
    font-size: 16px;
    font-weight: bold;
    margin-bottom: 20px;
}
</style>